<template>
  <div class="article-view">
    <el-tabs v-model="activeTab" type="card">
      <el-tab-pane label="文章列表" name="list">
        <el-table :data="articles" style="width: 100%">
          <el-table-column prop="title" label="标题" width="180" />
          <el-table-column prop="category_name" label="分类" width="180" />
          <el-table-column prop="create_time" label="创建时间" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button size="small" @click="handleLike(scope.row)"><el-icon><StarFilled :class="{'text-yellow-500': scope.row.isLiked}" :style="{color: scope.row.isLiked ? '#eab308' : ''}" /></el-icon></el-button>
              <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" class="add-btn" @click="activeTab = 'add'">新增文章</el-button>
      </el-tab-pane>

      <el-tab-pane label="新增文章" name="add">
        <el-form :model="form" label-width="80px">
          <el-form-item label="文章标题">
            <el-input v-model="form.title" />
          </el-form-item>
          <el-form-item label="文章分类">
            <el-select v-model="form.category_id" placeholder="请选择分类">
              <el-option 
                v-for="category in categories" 
                :key="category.id" 
                :label="category.name" 
                :value="category.id" 
              />
            </el-select>
          </el-form-item>
          <el-form-item label="文章内容">
            <el-input v-model="form.content" type="textarea" :rows="10" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">提交</el-button>
            <el-button @click="activeTab = 'list'">取消</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="编辑文章" name="edit">
        <el-form :model="editForm" label-width="80px">
          <el-form-item label="文章标题">
            <el-input v-model="editForm.title" />
          </el-form-item>
          <el-form-item label="文章分类">
            <el-select v-model="editForm.category_id" placeholder="请选择分类">
                <el-option
                    v-for="category in categories"
                    :key="category.id"
                    :label="category.name"
                    :value="category.id"
                />
            </el-select>
          </el-form-item>
          <el-form-item label="文章内容">
            <el-input v-model="editForm.content" type="textarea" :rows="10" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onEditSubmit">保存</el-button>
            <el-button @click="activeTab = 'list'">取消</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { StarFilled } from '@element-plus/icons-vue';
import {
  getArticleListService,
  createArticleService,
  updateArticleService,
  deleteArticleService, getCategoryListService
} from '@/api/article';
import {ElMessage, ElMessageBox} from 'element-plus';


const activeTab = ref('list');

const loading = ref(false);
const articles = ref([]);

onMounted(() => {
  fetchArticles();
  fetchCategories();
});

// 获取分类列表
const fetchCategories = async () => {
  try {
    const { data } = await getCategoryListService();
    categories.value = data;
  } catch (error) {
    console.error('获取分类列表失败:', error);
  }
};

// 获取文章列表
const fetchArticles = async () => {
  loading.value = true;
  try {
    const { data } = await getArticleListService();
    articles.value = data;
  } catch (error) {
    console.error('获取文章列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 分类列表
const categories = ref([]);

// 新增表单
const form = reactive({
  title: '',
  category_id: null,
  content: ''
});

// 编辑表单
const editForm = reactive({
  title: '',
  category_id: null,
  content: ''
});

// 提交表单
const onSubmit = async () => {
  try {
    const { data } = await createArticleService({
      title: form.title,
      category_id: form.category_id,
      content: form.content
    });
    
    articles.value.push({
      ...data,
      createTime: new Date().toLocaleDateString()
    });
    
    ElMessage.success('文章创建成功');
    activeTab.value = 'list';
    resetForm();
    await fetchArticles(); // 刷新文章列表
  } catch (error) {
    console.error('创建文章失败:', error);
    ElMessage.error(error.response?.data?.msg || '文章创建失败');
  }
};

const handleEdit = (row) => {
  // 编辑文章
  Object.assign(editForm, row);
  activeTab.value = 'edit';
};

// 编辑文章提交
const onEditSubmit = async () => {
  try {
    loading.value = true;
    await updateArticleService(editForm);
    await fetchArticles();
    ElMessage.success('文章更新成功');
    activeTab.value = 'list';
  } catch (error) {
    console.error('更新文章失败:', error);
    ElMessage.error(error.response?.data?.msg || '文章更新失败');
  } finally {
    loading.value = false;
  }
};

// 删除文章
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这篇文章吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    loading.value = true;
    await deleteArticleService(row.id);
    await fetchArticles();
    ElMessage.success('文章删除成功');
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除文章失败:', error);
      ElMessage.error(error.response?.data?.msg || '文章删除失败');
    }
  } finally {
    loading.value = false;
  }
};

// 点赞文章
const handleLike = (row) => {
  // 切换点赞状态
  const index = articles.value.findIndex(item => item.id === row.id);
  if (index !== -1) {
    articles.value[index].isLiked = !articles.value[index].isLiked;
  }
};

const resetForm = () => {
  // 重置表单
  form.title = '';
  form.category_id = null;
  form.content = '';
};
</script>

<style lang="scss" scoped>
.article-view {
  padding: 20px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  
  .add-btn {
    margin-top: 20px;
  }
}
</style>